package com.sgb.member.view_model;

import android.text.TextUtils;

import com.sgb.member.MemberConfig;
import com.sgb.member.di.repository.MemberRepertory;
import com.sgb.member.entity.ListMResponse;
import com.sgb.member.entity.MemberCentralizedEntity;
import com.sgb.member.entity.MemberCentralizedFactoryEntity;
import com.sgb.member.ui.fragment.BusinessCollectingFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.selection.CommonPopEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

public class BusinessCollectingModel extends BaseViewModel {

    private BusinessCollectingFragment fragment;
    private final MemberRepertory mRepertory;
    private final int maxPageSize = 10;
    private int current;
    private CommonPopEntity mAll;

    public BusinessCollectingModel(BusinessCollectingFragment activity, MemberRepertory repertory) {
        this.fragment = activity;
        this.mRepertory = repertory;

        mAll = new CommonPopEntity();
        mAll.setNo("");
        mAll.setTypeName("全部");
    }


    public void showOrHideDialog(boolean aBoolean) {
        if (aBoolean) {
            if (!DialogHelper.isShowing()) {
                DialogHelper.showProgressDialog(fragment.getActivity(), "数据获取中...");
            }
        } else {
            DialogHelper.dismissProgressDialog();
            fragment.closeRecyclerRefreshing();
        }
    }

    public void groupBuyList(boolean isLoadMore, String companyName,
                             String mNo0, String mNo1,
                             String mNo2, String mNo3, String mNo31,
                             String mNo4, String mNo5,
                             String mNo6, String mNo7, String mNo8,String level) {
        int currentPage = isLoadMore ? current + 1 : 1;
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("current", currentPage);
        map.put("page", currentPage);
        map.put("limit", maxPageSize);
        /*if(TextUtils.isEmpty(mNo8)){
            map.put("order", "1-"); //采购家数 倒序 order: "1-"   order: "1+"；报价家数 倒序 order: "2-"   order: "2+"
        } else {
            map.put("order", mNo8); //采购家数 倒序 order: "1-"   order: "1+"；报价家数 倒序 order: "2-"   order: "2+"
        }*/
        map.put("searchKey", companyName);
        map.put("groupbuyMode", mNo0);//1,需方集采，2企业专项
        map.put("groupBuyType", mNo1);// 集采方式（全部、汇集采购或者即报即采） 1即报集采 2 汇总集采
        map.put("status", mNo2); // 集采状态（全部、集采中、集采完成）
        map.put("groupbuyClass", mNo3);// 集采类型（全部、商品材料、机械租赁、设备租赁）
        map.put("typeNo", mNo31);// 最后一级类目类型
        map.put("offerType", mNo4);// 报价类型（全部、会员报价、市场报价）
        map.put("joinType", mNo5);// 加盟客户
        map.put("endDayType", mNo6); // 报价截止时间
        map.put("provinceNo", mNo7);
        map.put("cityNo", mNo8);
        map.put("level", level);
        mRepertory.getApi().groupBuyList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberCentralizedEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberCentralizedEntity>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberCentralizedEntity>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }

    public void groupBuyGFList(boolean isLoadMore, String companyName,
                               String mNo0, String mNo1,
                               String mNo2, String mNo3, String mNo31,String mNo32,String mNo33,
                               String mNo4, String mNo5,
                               String mNo6, String mNo7, String mNo8,String level) {
        int currentPage = isLoadMore ? current + 1 : 1;
        showOrHideDialog(true);
        Map<String, Object> map = new HashMap<>();
        map.put("current", currentPage);
        map.put("page", currentPage);
        map.put("limit", maxPageSize);
        map.put("searchKey", companyName); // 搜索内容
        map.put("provinceNo", mNo7); // 省级编号
        map.put("cityNo", mNo8); // 市级编号
        map.put("districtNo", ""); // 区级编号
        map.put("endTime", mNo6); // 截止时间
        map.put("firstType", mNo31); // 一级分类业务编号
        map.put("secondType", mNo32); // 二级分类业务编号
        map.put("thirdType", mNo33); // 三级分类业务编号
        map.put("status", mNo2);//集采状态
        map.put("level", level);
        map.put("timeIntervals", mNo6); // 时间筛选key
        mRepertory.getApi().getMemberSaleSearch(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberCentralizedFactoryEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberCentralizedFactoryEntity>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecyclerGF(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberCentralizedFactoryEntity>>>> call, Throwable t) {
                super.onFailure(call, t);
                if (!isLoadMore) {
                    fragment.showEmpty();
                }
            }

            @Override
            public void onFinally() {
                showOrHideDialog(false);
            }
        });
    }


    // 集采方式
    public void getCollectingMode(int type, boolean isShowLeftDialog) {
        List<CommonPopEntity> entityList = new ArrayList<>();
        // 1即报集采 2 汇总集采
        entityList.add(new CommonPopEntity("", "全部"));
        entityList.add(new CommonPopEntity("1", "即报即采"));
        entityList.add(new CommonPopEntity("2", "汇集采购"));
        if (isShowLeftDialog) {
            fragment.showLeftDialog(type, entityList);
        } else {
            fragment.setChooseItemData(type, entityList);
        }
    }

    // 集采类型
    public void getGroupBuyClassList(int type, boolean isShowLeftDialog) {
        showOrHideDialog(true);
        mRepertory.getApi().groupBuyClassList().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    data.getData().add(0, mAll);
                    fragment.updateTabLayout(data.getData());
                } else {
                    fragment.updateTabLayout(new ArrayList<>());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CommonPopEntity>>> call, Throwable t) {
                super.onFailure(call, t);
                fragment.updateTabLayout(new ArrayList<>());
            }
        });
    }

    // 集采状态
    public void getStatus(int type, boolean isShowLeftDialog) {
        showOrHideDialog(true);
        mRepertory.getApi().getStatus().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    data.getData().get(0).setNo(""); // 全部的key值为-1，
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, data.getData());
                    } else {
                        fragment.setChooseItemData(type, data.getData());
                    }
                }
            }
        });
    }

    //报价客户
    public void getOfferList(int type, boolean isShowLeftDialog) {
        List<CommonPopEntity> datas = new ArrayList<>();
        datas.add(new CommonPopEntity("", "全部"));
        datas.add(new CommonPopEntity("1", "客户报价"));
        datas.add(new CommonPopEntity("2", "市场报价"));
        datas.add(new CommonPopEntity("3", "成员报价"));
        if (isShowLeftDialog) {
            fragment.showLeftDialog(type, datas);
        } else {
            fragment.setChooseItemData(type, datas);
        }
    }

    //加盟客户
    public void getJoinTypeList(int type, boolean isShowLeftDialog) {
        List<CommonPopEntity> datas = new ArrayList<>();
        datas.add(new CommonPopEntity("", "全部"));
        datas.add(new CommonPopEntity("1", "客户加盟"));
        datas.add(new CommonPopEntity("2", "市场加盟"));
        datas.add(new CommonPopEntity("3", "成员加盟"));
        if (isShowLeftDialog) {
            fragment.showLeftDialog(type, datas);
        } else {
            fragment.setChooseItemData(type, datas);
        }
    }

    //集采时间
    public void showTimePopWindow(int type, boolean isShowLeftDialog) {
        showOrHideDialog(true);
        mRepertory.getApi().getDateTimeList().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getData() != null && data.getData().size() > 0) {
                    data.getData().add(0, mAll);
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, data.getData());
                    } else {
                        fragment.setChooseItemData(type, data.getData());
                    }
                }
            }
        });
    }

    /**
     * 获取省市区地址
     */
    public void getAddressModel(int type) {
        showOrHideDialog(true);
        mRepertory.getApi().getAddressEntityCityList().enqueue(new ICallBack<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> data) {
                showOrHideDialog(false);
                if (data != null && data.getData() != null && data.getData().size() > 0) {
                    List<CommonPopEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> datum : data.getData()) {
                        entities.add(new CommonPopEntity(datum.getNo(), datum.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    fragment.setChooseItemData(type, entities);
                    fragment.setAddressData(data.getData());
                }
            }
        });
    }

    public void getAddressCityData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData, String no, int type, boolean isShowLeftDialog) {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> scrDatum : scrData) {
            if (scrDatum.getId().equals(no)) {
                List<AddressEntity<List<AddressEntity>>> children = scrDatum.getChildren();
                if (children != null && children.size() > 0) {
                    List<CommonPopEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity>> child : children) {
                        entities.add(new CommonPopEntity(child.getNo(), child.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, entities);
                    } else {
                        fragment.setChooseItemData(type, entities);
                    }
                }
            }
        }
    }

    // 招标类型->获取类别下级所有树形数据
    public void getTenderGoodsCategoryAllList(int type, String category, boolean isShowLeftDialog) {
        showOrHideDialog(true);
        Call<BaseEntity<List<CommonPopEntity>>> call = null;
        if ("1".equals(category)) { // 商品材料
            call = mRepertory.getApi().getGoodCategory(mRepertory.getAreaCode());
        } else if ("2".equals(category)) { // 机械租赁
            call = mRepertory.getApi().getMachineCategory();
        } else if ("3".equals(category)) { // 设备租赁
            call = mRepertory.getApi().getEquipmentCategory();
        }
        if (call == null) {
            return;
        }
        call.enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    data.getData().add(0, mAll);
                    if (isShowLeftDialog) {
                        fragment.showLeftDialog(type, data.getData());
                    } else {
                        fragment.setChooseItemData(type, data.getData());
                    }
                }
            }
        });
    }

    public void getH5Url(String id) {
        showOrHideDialog(true);
        mRepertory.getApi().getUrlSetting("collection").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                String url = data.getData().getUrl() + "?id=" + id + "&type=0" + "&token=" + mRepertory.getToken();
                MemberConfig.getInstance().startWebViewX5(fragment.getActivity(), url);
            }
        });
    }

    /**
     * 供方发起查看H5详情页
     *
     * @param id
     */
    public void getH5UrlFactory(String id) {
        showOrHideDialog(true);
        mRepertory.getApi().getUrlSetting("Factory").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                String url = data.getData().getUrl() + "?id=" + id;
                MemberConfig.getInstance().startWebViewX5(fragment.getActivity(), url);
            }
        });
    }

    //会员级别
    public void getMemberLevelData() {
        mRepertory.getApi().getMemberLevelList().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    fragment.setMemberLevelData(data.getData());
                } else {
                    fragment.setMemberLevelData(new ArrayList<>());
                }
            }
        });
    }
}
